package org.magnerfuller.imtoolkit.server.session.medium;

import java.io.*;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.magnerfuller.imtoolkit.util.LazyReader;
import org.magnerfuller.imtoolkit.util.LazyReaderListener;

public class XMPPIMSessionMedium extends SessionMedium implements MessageListener, LazyReaderListener {
  
  private PipedInputStream inputStream;
  
  private PipedOutputStream outputStream;
  
  private LazyReader chatReader;
  
  private PrintWriter chatWriter;
  
  private Chat chatChannel;
  
  public XMPPIMSessionMedium(Chat chatChannel) throws IOException {
    this.chatChannel = chatChannel;
    
    inputStream = new PipedInputStream();
    outputStream = new PipedOutputStream();
    
    PipedInputStream chatInputStream = new PipedInputStream();
    chatInputStream.connect(outputStream);
    
    PipedOutputStream chatOutputStream = new PipedOutputStream();
    chatOutputStream.connect(inputStream);
    
    chatReader = new LazyReader(chatInputStream);
    chatWriter = new PrintWriter(chatOutputStream);
    
    chatReader.addListener(this);
    chatReader.start();
    
  }
	
	public InputStream getInputStream() throws IOException {
  	return inputStream;
	}
	
	public OutputStream getOutputStream() throws IOException {
		return outputStream;
	}

	public String getModuleName() {
	  return "xmpp";
	}

  public void processMessage(Chat chat, Message message) {
    // Take the message content and push it through the stream.
    chatWriter.write(message.getBody());
    chatWriter.flush();
  }

  public void handleReadLine(LazyReader source, String line) {
    // Write the line out over the chat protocol.
    try {
      chatChannel.sendMessage(line);
    } catch (Exception e) {
      System.err.println("XMPPIMSessionMedium::handleReadLine: Failed to send message.");
    }
  }
  
}
